<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue WebSocket 聊天室</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
    <script src="https://cdn.socket.io/4.0.1/socket.io.min.js"></script>
</head>
<body>
<div id="app">
    <h1>Vue WebSocket 聊天室</h1>
    <ul>
        <li v-for="(user, index) in users" :key="index">
            {{ user }} <button @click="kick(index)">踢出</button>
        </li>
    </ul>
    <input type="text" v-model="message" @keyup.enter="sendMessage">
    <button @click="sendMessage">发送</button>
    <ul>
        <li v-for="(msg, index) in messages" :key="index">{{ msg }}</li>
    </ul>
</div>
<script>
    new Vue({
        el: '#app',
        data: {
            users: [],
            messages: [],
            message: '',
            socket: null,
            username: ''
        },
        created() {
            this.socket = new WebSocket("ws://localhost:9985");
            this.socket.on('connect', () => {
                this.socket.emit('join', this.username);
            });
            this.socket.on('updateUsers', (users) => {
                this.users = users;
            });
            this.socket.on('newMessage', (msg) => {
                this.messages.push(msg);
            });
            this.socket.on('disconnect', () => {
                this.users = this.users.filter(user => user !== this.username);
                this.messages = [];
            });
        },
        methods: {
            sendMessage() {
                if (this.message) {
                    this.socket.emit('newMessage', this.username + ': ' + this.message);
                    this.message = '';
                }
            },
            kick(index) {
                const user = this.users[index];
                this.socket.emit('kick', user);
                this.users = this.users.filter(u => u !== user);
            }
        }
    });
</script>
</body>
</html>
